
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.UKIT.airtickets.DB.UserFavoriteDao
import com.UKIT.airtickets.R
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.Service.Tikets
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.text.SimpleDateFormat
import java.util.Locale

class TicketAdapter(private val onFavoriteClickListener: OnFavoriteClickListener, private val userFavoriteDao: UserFavoriteDao) : RecyclerView.Adapter<TicketAdapter.TicketViewHolder>() {

    interface OnFavoriteClickListener {
        fun onFavoriteClick(ticket: Tikets)
    }

    private val diffCallback = object : DiffUtil.ItemCallback<Tikets>() {
        override fun areItemsTheSame(oldItem: Tikets, newItem: Tikets): Boolean {
            return oldItem.searchToken == newItem.searchToken
        }

        override fun areContentsTheSame(oldItem: Tikets, newItem: Tikets): Boolean {
            return oldItem == newItem
        }
    }

    private val differ = AsyncListDiffer(this, diffCallback)

    fun setData(newList: List<Tikets>) {
        differ.submitList(newList)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TicketViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_ticket, parent, false)
        return TicketViewHolder(view, userFavoriteDao)
    }

    override fun onBindViewHolder(holder: TicketViewHolder, position: Int) {
        val ticket = differ.currentList[position]
        holder.bind(ticket)

        holder.likeImageView.setOnClickListener {
            onFavoriteClickListener.onFavoriteClick(ticket)
            val isInFavorite = isInFavorites(ticket)

            if (isInFavorite) {
                holder.likeImageView.setImageResource(R.drawable.ic_like)
            } else {
                holder.likeImageView.setImageResource(R.drawable.ic_like_fill)
            }
        }

    }

    fun isInFavorites(ticket: Tikets): Boolean {
        val searchToken = ticket.searchToken
        val userId = SettingsApp.userId

        val count = runBlocking(Dispatchers.IO) {
            userFavoriteDao.isFavorite(searchToken, userId)
        }

        return count > 0
    }

    override fun getItemCount(): Int {
        return differ.currentList.size
    }

    class TicketViewHolder(itemView: View, private var userFavoriteDao: UserFavoriteDao) : RecyclerView.ViewHolder(itemView) {

        private val priceTextView: TextView = itemView.findViewById(R.id.priceTextView)
        private val departureTimeTextView: TextView =
            itemView.findViewById(R.id.departureTimeTextView)
        private val durationTextView: TextView = itemView.findViewById(R.id.durationTextView)
        private val arrivalTimeTextView: TextView = itemView.findViewById(R.id.arrivalTimeTextView)
        private val departureCodeTextView: TextView =
            itemView.findViewById(R.id.departureCodeTextView)
        private val arrivalCodeTextView: TextView = itemView.findViewById(R.id.arrivalCodeTextView)
        val likeImageView: ImageView = itemView.findViewById(R.id.likeImageView)

        @SuppressLint("SetTextI18n")
        fun bind(ticket: Tikets) {
            val isInFavorites = isInFavorites(ticket)
            priceTextView.text = "${ticket.price.toString()} ₽"
            departureTimeTextView.text = getTime(ticket.startDate)
            durationTextView.text = "${getFlightDuration(ticket.startDate, ticket.endDate)} в пути / Без пересадок"
            arrivalTimeTextView.text = getTime(ticket.endDate)
            departureCodeTextView.text = ticket.startCityCode.uppercase()
            arrivalCodeTextView.text = ticket.endCityCode.uppercase()
            val imageResource = if (isInFavorites) {
                R.drawable.ic_like_fill
            } else {
                R.drawable.ic_like
            }
            likeImageView.setImageResource(imageResource)
        }

        private fun isInFavorites(ticket: Tikets): Boolean {
            val searchToken = ticket.searchToken
            val userId = SettingsApp.userId

            val count = runBlocking(Dispatchers.IO) {
                userFavoriteDao.isFavorite(searchToken, userId)
            }

            return count > 0
        }


        private fun getTime(str: String): String {
            val parts = str.split("T")

            if (parts.size >= 2) {
                val timePart = parts[1]

                val timeComponents = timePart.split(":")

                if (timeComponents.size >= 2) {
                    val hours = timeComponents[0]
                    val minutes = timeComponents[1]

                    return "$hours:$minutes"
                }
            }
            return ""
        }

        @SuppressLint("DefaultLocale")
        fun getFlightDuration(startDate: String, endDate: String): String {
            val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())

            try {
                val startTime = dateFormat.parse(startDate)
                val endTime = dateFormat.parse(endDate)

                val durationMillis = endTime.time - startTime.time

                val days = durationMillis / (1000 * 60 * 60 * 24)
                val hours = (durationMillis % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
                val minutes = (durationMillis % (1000 * 60 * 60)) / (1000 * 60)

                return String.format("%d дней %02d:%02d", days, hours, minutes)
            } catch (e: Exception) {
                e.message?.let { Log.e("E", it) }
            }
            return ""
        }
    }
}
